﻿using System;
using System.Data;
using System.Windows.Forms;
using System.IO;
using YNCNumberSys.ZJClass;
using myDBConnection = System.Data.SqlClient.SqlConnection;
using myDBTransaction = System.Data.SqlClient.SqlTransaction;
using YNCNumberSys.db;
using YNCNumberSys.DbDal;
using YNCNumberSys.Entity;
using cadApp = Autodesk.AutoCAD.ApplicationServices.Application;
using static Autodesk.AutoCAD.Windows.OpenFileDialog;
using C1.Win.C1FlexGrid;
using common;

namespace YNCNumberSys
{
    /// <summary>
    /// 4C图号申请。
    /// </summary>
    public partial class Apply4CNumber : Form
    {
        private string s_用户名;
        public string str_用户名
        {
            get { return s_用户名; }
            set
            {
                s_用户名 = value;
                this.tbx_用户名.Text = value;
            }
        }

        public Apply4CNumber()
        {
            InitializeComponent();
            tbx_设计日期.Text = System.DateTime.Now.ToString("yyyy-MM-dd");
            string filePath = System.Reflection.Assembly.GetExecutingAssembly().Location;
            string file = Path.Combine(Path.GetDirectoryName(filePath), "config.ini");
            if (File.Exists(file))
            {
                FileIni t = new FileIni(file);
                string regKey = t.ReadValue("配置", "4C机床");
                if (!string.IsNullOrEmpty(regKey))
                {
                    tbx_机床型号.Text = regKey;
                }

                string regKey2 = t.ReadValue("配置", "4CA号");
                if (!string.IsNullOrEmpty(regKey2))
                {
                    tbx_A号.Text = regKey2;
                }

                string regKey3 = t.ReadValue("配置", "4C文件夹");
                if (!string.IsNullOrEmpty(regKey3))
                {
                    tbx_路径.Text = regKey3;
                }
            }
        }

        /// <summary>
        /// 清空列表空间。
        /// </summary>
        void ClearFlexs()
        {
            m_flex.BeginUpdate();
            m_flex.DataSource = null;
            m_flex.Rows.Count = 1;
            m_flex.Cols.Count = 1;
            m_flex.EndUpdate();
            m_flexO.BeginUpdate();
            m_flex.DataSource = null;
            m_flex.Rows.Count = 1;
            m_flex.Cols.Count = 1;
            m_flexO.EndUpdate();
        }
        /// <summary>
        ///  取得文件夹路劲下的所有文件。
        /// </summary>
        /// <param name="fPath">文件夹</param>
        private void GetFolder(string fPath)
        {
            ClearFlexs();
            tbx_路径.Text = fPath;
            DirectoryInfo folder = new DirectoryInfo(fPath);
            this.tbx_路径.Text = fPath;
            if (folder.Exists)
            {
                FileInfo[] files= folder.GetFiles();
                TempFolderDal dal = new TempFolderDal();
                string error = string.Empty;
                DataTable dt=dal.FileInfoTable(files, false,ref error);
                if(dt.Rows.Count>=1)
                {
                    m_flexO.DataSource = dt;
                    for (int r = 1; r < m_flexO.Rows.Count; r++)
                        m_flexO[r, 0] = r;
                    m_flexO.AutoSizeCols();
                    m_flexO.AutoSizeRows();
                    labelOrgin.Text = "共计:" + dt.Rows.Count + "条记录";
                    DataTable staticDt = dal.StaticInfoTable(dt);
                    m_flex.DataSource = staticDt;
                    for (int r = 1; r < m_flex.Rows.Count; r++)
                        m_flex[r, 0] = r;
                    labelStatic.Text = "共计:" + staticDt.Rows.Count + "条记录";
                    m_flex.AutoSizeCols();
                    m_flex.AutoSizeRows();
                    this.tabControl1.SelectedTab = tabPageOrigin; // XSL Add 2023 05
                }
                if (!string.IsNullOrEmpty(error))
                {
                    cadApp.ShowAlertDialog(error);
                }
            }
        }
        /// <summary>
        /// 界面操作，刷新按钮。
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonRefresh_Click(object sender, EventArgs e)
        {
            if(Directory.Exists(this.tbx_路径.Text))
                GetFolder(this.tbx_路径.Text);
            else
                cadApp.ShowAlertDialog("路径不存在！");
        }
        /// <summary>
        /// 界面操作，选择文件夹。
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_选择文件夹_Click(object sender, EventArgs e)
        {
            this.tbx_路径.Text = "";
            if (this.folderBrowserDialog.ShowDialog() == DialogResult.OK)
                GetFolder(this.folderBrowserDialog.SelectedPath);
        }
        /// <summary>
        /// 系统要号，内部调用存储过程：
        /// （1）Lock USER
        /// （2）建立文件的临时文件夹，创建对应的Table TempFolder
        /// （3）CheckFileNo
        /// （4）调用存储过程，内部逻辑：分配图号，已经分配过的，不进行分配。未分配过的，进行分配。
        /// （5）文件重新命名。FilesCopyNewAndDelete
        /// （6）重新设置标题栏。SetTitle。
        /// （7）unLock USER
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_执行_Click(object sender, EventArgs e)
        {
            this.labelResult.Text = "共计:" + 0 + "条记录。";
            this.labelCheck.Text = "共计:" + 0 + "条记录。";
            if (m_flexO.DataSource==null)
            {
                cadApp.ShowAlertDialog("请【选择】或【刷新】文件夹！");
                return;
            }
            m_flexResut.BeginUpdate();
            m_flexResut.DataSource = null;
            m_flexResut.Rows.Count = 1;
            m_flexResut.Cols.Count = 1;
            m_flexResut.EndUpdate();
            tabPageResut.ImageIndex = -1;

            m_flexCheck.BeginUpdate();
            m_flexCheck.DataSource = null;
            m_flexCheck.Rows.Count = 1;
            m_flexCheck.Cols.Count = 1;
            m_flexCheck.EndUpdate();
            tabPageChk.ImageIndex = -1;
            this.buttonReport.Enabled = false;

            if (tbx_路径.Text == string.Empty)
            {
                cadApp.ShowAlertDialog("请选择文件夹！");
                return;
            }
            if (string.IsNullOrEmpty(tbx_机床型号.Text.Trim()))
            {
                cadApp.ShowAlertDialog("机床型号不能为空！");
                return;
            }
            if (string.IsNullOrEmpty(tbx_A号.Text.Trim()))
            {
                cadApp.ShowAlertDialog("A号不能为空！");
                return;
            }
            StatusDal statusDal = new StatusDal();
            string isLock = statusDal.IsLock(s_用户名);
            if (isLock!= "ok")
            {
                cadApp.ShowAlertDialog(isLock);
                return;
            }
            else
            {
                DataTable dtLock = statusDal.Lock(s_用户名);
                if (checkBoxIncreaseMode.Checked)//if (dtLock.Rows.Count==1) //XSL  2023 05
                {
                    if((string)dtLock.Rows[0]["user"]== s_用户名)
                    {
                        DataTable dtFolder = (DataTable)m_flexO.DataSource;
                        TempFolderDal folderDal = new TempFolderDal();
                        folderDal.InsertTempFolder(dtFolder);
                        Apply4CNumberDal ApDal = new Apply4CNumberDal();
                        DateTime t1 = DateTime.Now;
                        DataTable dtCheck = ApDal.CheckFileNo(tbx_机床型号.Text.Trim(),tbx_A号.Text.Trim(), s_用户名);
                        if(checkBoxIncreaseMode.Checked)//?? if(dtCheck.Rows.Count==0)
                        {
                            t1 = DateTime.Now;
                            DataTable dt;
                            if(this.checkBoxIncreaseMax.Checked)
                                dt = ApDal.ExecuteStoredProcedureMaxIncrease(
                                        tbx_机床型号.Text.Trim(),
                                        tbx_A号.Text.Trim(),
                                        string.Empty,
                                        string.Empty,
                                        s_用户名,
                                        tbx_审核人.Text.Trim(),
                                        0,
                                        string.Empty);
                            else
                                dt = ApDal.ExecuteStoredProcedure(
                                            tbx_机床型号.Text.Trim(),
                                            tbx_A号.Text.Trim(),
                                            string.Empty,
                                            string.Empty,
                                            s_用户名,
                                            tbx_审核人.Text.Trim(),
                                            0,
                                            string.Empty);
                            m_flexResut.DataSource = dt;
                            DateTime t2 = DateTime.Now;
                            TimeSpan tPan = t2 - t1;
                            if (dt != null)
                            {
                                this.labelResult.Text = string.Format("耗时{0}h{1}m{2}.{3}s，", tPan.Hours, tPan.Minutes, tPan.Seconds, t1.Millisecond) + "共计:" + dt.Rows.Count + "条记录。";
                                this.labelCheck.Text = "共计:" + 0 + "条记录";
                                if (m_flexResut.Cols.Contains("ID"))
                                    m_flexResut.Cols["ID"].Visible = false;
                                if (m_flexResut.Cols.Contains("名称"))
                                    m_flexResut.Cols["名称"].Visible = false;
                                if (m_flexResut.Cols.Contains("规格"))
                                    m_flexResut.Cols["规格"].Visible = false;
                                if (m_flexResut.Cols.Contains("外协"))
                                    m_flexResut.Cols["外协"].Visible = false;
                                if (m_flexResut.Cols.Contains("外协单位"))
                                    m_flexResut.Cols["外协单位"].Visible = false;
                                if (m_flexResut.Cols.Contains("作废"))
                                    m_flexResut.Cols["作废"].Visible = false;
                                tabPageResut.ImageIndex = 1;
                                for (int r = 1; r < m_flexResut.Rows.Count; r++)
                                {
                                    m_flexResut[r, 0] = r;
                                }

                            }
                            m_flexResut.AutoSizeCols();
                            m_flexResut.AutoSizeRows();
                            this.tabControl1.SelectedTab = this.tabPageResut;
                            //复制文件，删除源文件
                            CadHelperDal.FilesCopyNewAndDelete(dt, tbx_路径.Text, false);
                            //设置BOM,同时更新数据库
                            if (dt.Rows.Count > 0)
                                CadHelperDal.SetTitle(tbx_路径.Text, dt);
                            m_flexResut.AutoSizeCols();
                            m_flexResut.AutoSizeRows();
                            if (dt.Rows.Count > 0)
                                this.tabControl1.SelectedTab = this.tabPageResut;
                            this.tabControl1.SelectedTab = this.tabPageResut;
                            DateTime t3 = DateTime.Now;
                            tPan = t3 - t2;
                            this.labelResult.Text = this.labelResult.Text + string.Format(@"处理图纸耗时{0}h{1}m{2}.{3}s。",
                                tPan.Hours, tPan.Minutes, tPan.Seconds, t1.Millisecond);

                            m_flexCheck.DataSource = dtCheck;
                            t2 = DateTime.Now;
                            tPan = t2 - t1;
                            if (dtCheck!=null)
                            {
                                this.labelCheck.Text = string.Format("耗时{0}h{1}m{2}.{3}s，", tPan.Hours, tPan.Minutes, tPan.Seconds, t1.Millisecond) + "共计:" + dtCheck.Rows.Count + "条记录。";
                                this.labelResult.Text = "共计:" + 0 + "条记录";
                                if (m_flexCheck.Cols.Contains("ID"))
                                    m_flexCheck.Cols["ID"].Visible = false;
                                if (m_flexCheck.Cols.Contains("名称"))
                                    m_flexCheck.Cols["名称"].Visible = false;
                                if (m_flexCheck.Cols.Contains("规格"))
                                    m_flexCheck.Cols["规格"].Visible = false;
                                if (m_flexCheck.Cols.Contains("外协"))
                                    m_flexCheck.Cols["外协"].Visible = false;
                                if (m_flexCheck.Cols.Contains("外协单位"))
                                    m_flexCheck.Cols["外协单位"].Visible = false;
                                if (m_flexCheck.Cols.Contains("作废"))
                                    m_flexCheck.Cols["作废"].Visible = false;
                                for (int r = 1; r < m_flexCheck.Rows.Count; r++)
                                {
                                    m_flexCheck[r, 0] = r;
                                }
                            }
                            m_flexCheck.AutoSizeCols();
                            m_flexCheck.AutoSizeRows();
                            this.tabControl1.SelectedTab = tabPageChk;
                            tabPageChk.ImageIndex = 0;
                        }
                        else
                        {
                            m_flexCheck.DataSource = dtCheck;
                            DateTime t2 = DateTime.Now;
                            TimeSpan tPan = t2 - t1;
                            if (dtCheck != null)
                            {
                                this.labelCheck.Text = string.Format("耗时{0}h{1}m{2}.{3}s，", tPan.Hours, tPan.Minutes, tPan.Seconds, t1.Millisecond) + "共计:" + dtCheck.Rows.Count + "条记录。";
                                this.labelResult.Text = "共计:" + 0 + "条记录";
                                if (m_flexCheck.Cols.Contains("ID"))
                                    m_flexCheck.Cols["ID"].Visible = false;
                                if (m_flexCheck.Cols.Contains("名称"))
                                    m_flexCheck.Cols["名称"].Visible = false;
                                if (m_flexCheck.Cols.Contains("规格"))
                                    m_flexCheck.Cols["规格"].Visible = false;
                                if (m_flexCheck.Cols.Contains("外协"))
                                    m_flexCheck.Cols["外协"].Visible = false;
                                if (m_flexCheck.Cols.Contains("外协单位"))
                                    m_flexCheck.Cols["外协单位"].Visible = false;
                                if (m_flexCheck.Cols.Contains("作废"))
                                    m_flexCheck.Cols["作废"].Visible = false;
                                for (int r = 1; r < m_flexCheck.Rows.Count; r++)
                                {
                                    m_flexCheck[r, 0] = r;
                                }
                            }
                            m_flexCheck.AutoSizeCols();
                            m_flexCheck.AutoSizeRows();
                            this.tabControl1.SelectedTab = tabPageChk;
                            tabPageChk.ImageIndex = 0;
                        }
                    }
                }
                else
                {
                    tabPageChk.ImageIndex = -1;
                }
                statusDal.UnLock(s_用户名);
            }
            for (int r = 1; r < m_flex.Rows.Count; r++)
            {
                m_flex[r, 0] = r;
            }
            m_flex.AutoSizeCols();
            m_flex.AutoSizeRows();
            bool enableFlag = false;
            if(m_flexResut.DataSource != null)
            {
                if (((DataTable)m_flexResut.DataSource).Rows.Count >= 1)
                    enableFlag = true;
            }
            if (m_flexCheck.DataSource != null)
            {
                if (((DataTable)m_flexCheck.DataSource).Rows.Count >= 1)
                    enableFlag = true;
            }
            this.buttonReport.Enabled = enableFlag;
       }
        /// <summary>
        /// 导出申请要号的结果明细，包含本次成功的要号、失败的要号。
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonReport_Click(object sender, EventArgs e)
        {
            if (m_flexCheck.DataSource != null || m_flexResut.DataSource != null)
            {
                SaveFileDialog saveImageDialog = new SaveFileDialog();
                saveImageDialog.Filter = "Excel Files (*.xls)|*.xls";
                saveImageDialog.Title = @"导出日志";
                saveImageDialog.FileName = DateTime.Now.ToString("yyMMdd_") + tbx_机床型号.Text.Trim() + "_" + tbx_A号.Text.Trim();

                if (saveImageDialog.ShowDialog() == DialogResult.OK)
                {
                    string savePath = saveImageDialog.FileName;
                    if (m_flexCheck.DataSource != null)
                        m_flexCheck.SaveExcel(savePath, @"重号明细", FileFlags.IncludeFixedCells);
                    if (m_flexResut.DataSource != null)
                        m_flexResut.SaveExcel(savePath, @"成功明细", FileFlags.IncludeFixedCells);
                }
            }
        }
        /// <summary>
        /// 退出时保留最后一次运行系统配置。
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ApplyNumber_FormClosed(object sender, FormClosedEventArgs e)
        {
            StatusDal statusDal = new StatusDal();
            statusDal.UnLock(s_用户名);
            string filePath = System.Reflection.Assembly.GetExecutingAssembly().Location;
            string file = Path.Combine(Path.GetDirectoryName(filePath), "config.ini");
            if (File.Exists(file))
            {
                FileIni t = new FileIni(file);
                t.WriteValue("配置", "4C机床", tbx_机床型号.Text);
                t.WriteValue("配置", "4CA号", tbx_A号.Text);
                t.WriteValue("配置", "4C文件夹", tbx_路径.Text);
            }

        }
        /// <summary>
        /// 导出EXCEL目录。
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonExportExcel_Click(object sender, EventArgs e)
        {
            OutExcelForm dlg = new OutExcelForm();
            dlg.Jch = tbx_机床型号.Text.Trim();
            dlg.Ah = tbx_A号.Text.Trim();
            dlg.Check4C = true;
            dlg.ShowDialog();
        }
    }
}
